﻿using Caliburn.Micro;
using MusicExplorer.Common;
using MusicExplorer.Model;
using MusicExplorer.Repository;
using MusicExplorer.Repository.Interfaces;
using MusicExplorer.ViewModels.Wrappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;

namespace MusicExplorer.ViewModels
{
    public sealed class RepositoryPageViewModel : PageViewModelBase
    {
        private readonly BindableCollection<GenreTileViewModel> m_genres;
        private Model.Repository m_repository;

        public RepositoryPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            m_genres = new BindableCollection<GenreTileViewModel>();
        }

        protected override async void OnInitialize()
        {
            ShowLoading();

            m_repository = ((RepositoryPageNavigationObject)Parameter).Repository;

            var repository = RepositoryBase.GetInstance(m_repository);
            Title = m_repository.Name;

            try
            {
                // Genres loading
                if (repository.SupportQuery(new QueryDefinition(QueryType.AllTracks, EntityType.Genre)))
                {
                    var genres = (await repository.GetAllEntitiesAsync(EntityType.Genre, m_tokenSource.Token)).OfType<Genre>();
                    if (genres != null && genres.Any() && !m_tokenSource.IsCancellationRequested)
                    {
                        foreach (var genre in genres)
                        {
                            m_genres.Add(new GenreTileViewModel(this, genre));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (!m_tokenSource.IsCancellationRequested)
                    RedirectToError(ex);
            }

            HideLoading();
        }

        public void NavigateToTracks(ItemClickEventArgs eventArgs)
        {
            var entityFilter = (EntityTileViewModel)eventArgs.ClickedItem;

            var group = new QueryGroup(Guid.NewGuid());
            group.Name = entityFilter.DisplayName;
            group.QueryType = QueryType.AllTracks;
            group.Entities.Add(entityFilter.Entity);

            m_navigationService.NavigateToViewModel<TracksPageViewModel>(new TracksPageNavigationObject()
            {
                Root = Root,
                SourcePage = this,
                Group = group
            });
        }

        public BindableCollection<GenreTileViewModel> Genres { get { return m_genres; } }
    }
}
